﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using net.windward.util;
using log4net;
using Microsoft.SharePoint;

namespace ArrowWebParts
{
    public class DashboardWidgetWebPart : WebPart
    {
        #region fields

        private bool isLicensed = false;

        private string rptDefUrl = "about:blank";
        [Personalizable(PersonalizationScope.User),
       WebBrowsable(false)]
        public string ReportDefinitionUrl
        {
            get { return rptDefUrl; }
            set { rptDefUrl = value; }
        }

        private int refreshTime = 0;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        public int RefreshTime
        {
            get { return refreshTime; }
            set { refreshTime = value; }
        }

        private int frameHeight = 0;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        public int FrameHeight
        {
            get { return frameHeight; }
            set { frameHeight = value; }
        }

        private bool scrollbarDisplay = true;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        public bool ScrollbarDisplay
        {
            get { return scrollbarDisplay; }
            set { scrollbarDisplay = value; }
        }

        private string defaultVariableValue = "0";
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        public string DefaultVariableValue
        {
            get { return defaultVariableValue; }
            set { defaultVariableValue = value; }
        }

        private Guid siteGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid SiteGuid
        {
            get { return siteGuid; }
            set { siteGuid = value; }
        }

        private Guid docLibGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid DocLibGuid
        {
            get { return docLibGuid; }
            set { docLibGuid = value; }
        }

        private Guid fileGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid FileGuid
        {
            get { return fileGuid; }
            set { fileGuid = value; }
        }

        private string id1;
        /// <summary>
        /// the log
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(DashboardWidgetWebPart));

        #endregion

        private IDashboardProvider dashboardProvider;
        [ConnectionConsumer("Dashboard Variables")]
        public void RegisterDashboardProvider(IDashboardProvider provider)
        {
            this.dashboardProvider = provider;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (log.IsDebugEnabled)
                log.Debug("Creating child controls");

            try
            {
                // read in license from web.config
                ArrowUtils.InitializeArrow(string.Concat(Page.Request.PhysicalApplicationPath, "\\web.config"));
                isLicensed = true;
            }
            catch (LicenseException lex)
            {
                ArrowUtils.LogFatalException(log, lex);
                Controls.Clear();
                Controls.Add(new LiteralControl(string.Format("License Error: {0}", lex.Message)));
                return;
            }

            try
            {
                if(ReportDefinitionUrl == "about:blank")
                {
                    Controls.Clear();
                    Controls.Add((new LiteralControl("Please select a valid report definition/template.")));
                    if (log.IsDebugEnabled)
                        log.Debug("Finished creating child controls.");
                    return;
                }

                id1 = UniqueID + "WRFrame";

                string error;
                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> var general_height_" + id1 + "=" + FrameHeight + "; function calcHeight" + id1 + "() { var the_height=document.getElementById(\"" + id1 + "\").contentWindow.document.body.scrollHeight;  if(general_height_" + id1 + "<=0){general_height_" + id1 + "=the_height+35;} document.getElementById(\"" + id1 + "\").height=general_height_" + id1 + ";}</script>"));
                Controls.Add(createFrameLiteralControl(id1, generateUrl(ArrowUtils.GetReportDefFromFile(ReportDefinitionUrl, out error), ReportDefinitionUrl), ScrollbarDisplay));

                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function setRefreshTimer" + id1 + "() { setTimeout('refreshFrame" + id1 + "()'," + (RefreshTime * 1000).ToString() + ") } </script>")); // function to set timer
                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function refreshFrame" + id1 + "() { if(document.frames['" + id1 + "'].location.href==\"about:blank\") {document.frames['" + id1 + "'].location.href=\"" + ReportDefinitionUrl + "\"; } else {document.frames['" + id1 + "'].location.reload();} setRefreshTimer" + id1 + "(); }</script>")); // function to refresh
                if (refreshTime > 0)
                    Controls.Add(new LiteralControl("<script type=\"text/javascript\"> mytime = setTimeout('refreshFrame" + id1 + "()'," + (RefreshTime * 1000).ToString() + ") </script>")); // start the refresh
            }
            catch (Exception e)
            {
                Controls.Clear();
                Controls.Add(new LiteralControl("Error: " + e.Message));
                ArrowUtils.LogFatalException(log, e);
            }

            if (log.IsDebugEnabled)
                log.Debug("Finished creating child controls.");
        }

        #region iframe

        private LiteralControl createFrameLiteralControl(string id, string url, bool displayScrollbar)
        {
            if (displayScrollbar)
                return new LiteralControl("<iframe ID=\"" + id + "\" src=\"" + url + "\" runat=\"server\" width=\"100%\" height=\"0px\" onLoad=\"calcHeight" + id + "();\" frameborder=\"0\"> </iframe>");
            
            return new LiteralControl("<iframe ID=\"" + id + "\" src=\"" + url + "\" runat=\"server\" width=\"100%\" height=\"0px\" onLoad=\"calcHeight" + id + "();\" frameborder=\"0\" scrolling=\"no\" > </iframe>");
            //return new LiteralControl("<iframe ID=\"WRFrame\" name=\"WRFrameName\" src=\"" + DisplayUrl + "\" runat=\"server\" width=\"100%\" height=\"400px\" onLoad=\"calcHeight();\"> </iframe>");
        }

        #endregion

        public override EditorPartCollection CreateEditorParts()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating editor parts.");

            try
            {
                List<EditorPart> editorParts = new List<EditorPart>(1);
                EditorPart part = new DashboardWidgetEditorPart();
                part.ID = ID + "_dashboardWidgetEditor";
                editorParts.Add(part);
                EditorPartCollection baseParts = base.CreateEditorParts();

                if (log.IsDebugEnabled)
                    log.Debug("Finished creating editor parts.");

                return new EditorPartCollection(baseParts, editorParts);
            }
            catch (Exception ex)
            {
                ArrowUtils.LogFatalException(log, ex);
                throw;
            }
        }

        private string generateUrl(ReportDefinition rai, string rptDefPath)
        {
            Dictionary<string, string> presetParameters;
            try
            {
                presetParameters = dashboardProvider.VariableValues;
            }
            catch (Exception)
            {
                throw new Exception("Please set a web part connection from a 'Dashboard Controller' web part to this dashboard widget.");
            }
            
            /*string[] parameterKeys = (string[])ViewState["kpdKeys"];
            string[] parameterValues = (string[])ViewState["kpdValues"];
            Dictionary<string, string> presetParameters = new Dictionary<string, string>();
            if ((parameterKeys != null) && (parameterValues != null))
            {
                for (int i = 0; i < parameterKeys.Length; i++)
                {
                    presetParameters.Add(parameterKeys[i], parameterValues[i]);
                }
            }*/

            string url = SPContext.Current.Web.Url;
            url += "/_layouts/DisplayReport.aspx" +
                "?rptDef=" + rptDefPath +
                "&format=" + "HTML" +
                "&numvars=" + rai.variableNameArray.Length;

            for (int i = 0; i < rai.variableNameArray.Length; i++)
            {
                if (presetParameters.ContainsKey(rai.variableNameArray[i]))
                {
                    string varValue;
                    presetParameters.TryGetValue(rai.variableNameArray[i], out varValue);
                    url += "&var" + i + "=" + varValue;
                }
                else
                {
                    url += "&var" + i + "=" + DefaultVariableValue;
                }

                /*else
                {
                    if (variableTypeLabelArray[i].Text == "Select")
                    {
                        url += "&var" + i.ToString() + "=" + variableValueDropDownListArray[i].SelectedValue;
                    }
                    else
                    {
                        url += "&var" + i.ToString() + "=" + variableValueTextBoxArray[i].Text.Trim();
                    }
                }*/
            }
            return url;
        }
    }
}
